package cn.tinlan.shopcoin.app.mine.adress;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.ConvertUtil;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;

import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;

/**
 * Created by Mortimer on 2018/12/19. 13:46
 * 佛祖🙏，永无bug。
 */
public class AddressActivity extends BaseActivity {
    @BindView(R.id.address_ae_title)
    TitleBar aeTitleBar;
    @BindView(R.id.address_ae_name)
    EditText aeNameET;
    @BindView(R.id.address_ae_tel)
    EditText aeTelET;
    @BindView(R.id.address_ae_address)
    EditText aeAddressET;
    @BindView(R.id.address_ae_setda)
    ImageView aeSetDfaultAddressIMG;

    @BindView(R.id.address_ae_delete)
    EditText address_ae_delete;


    public static final int RESULT_CODE = 1346;

    private boolean isUp = false;
    private String aeID;
    private String status = "0";
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_address_ae;
    }

    @Override
    public void initView() {
        super.initView();

        isUp = getIntent().getBooleanExtra("up_address",false);
        aeID = getIntent().getStringExtra("id");

        initTitleBar();
        initAEImg();
        initFootView();

    }

    private void initFootView() {
        if (isUp){
            address_ae_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteAddress();
                }
            });
        }else {
            address_ae_delete.setVisibility(View.GONE);
        }

    }

    private void initAEImg() {
        aeSetDfaultAddressIMG.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.isSelected()) {
                    status = "1";
                }else {
                    status = "0";
                }
            }
        });
    }



    private void initTitleBar() {
        aeTitleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {
                upAddress(isUp);
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
    }

    private void upAddress(final boolean up) {


        String name     = aeNameET.getText().toString().trim();
        String tel      = aeTelET.getText().toString().trim();
        if (!ConvertUtil.isMobileNumber(tel)){
            ToastUtils.show("请输入正确的手机号");
            return;
        }
        String address  = aeAddressET.getText().toString().trim();
        if (address.isEmpty()) {
            ToastUtils.show("请填写地址");
            return;
        }

        HttpParams params = new HttpParams();
        if (up){
            params.put("id",aeID);
        }
        if (status == "1") {
            setDefaultAddress();
        }
        params.put("user_id", SPUtils.getUserID(AddressActivity.this));
        params.put("name",name);
        params.put("tel",tel);
        params.put("zone",address);
        params.put("address",address);
        params.put("status",status);
        EasyHttp.post(Constants.UserDelAddress)
                .params(params)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        //请求错误
                    }

                    @Override
                    public void onSuccess(String response) {
                        if (up) {
                            ToastUtils.show("修改成功");
                        }else {
                            ToastUtils.show("添加成功");
                        }
                        Intent intent = new Intent();
                        setResult(RESULT_CODE, intent);
                        finish();
                    }

                }) {
                });
    }

    private void setDefaultAddress() {
        EasyHttp.post(Constants.UserDelAddress)
                .params("user_id",SPUtils.getUserID(AddressActivity.this))
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        //请求错误
                    }

                    @Override
                    public void onSuccess(String response) {

                    }

                }) {
                });
    }

    private void deleteAddress() {
        EasyHttp.post(Constants.UserDelAddress)
                .params("id",aeID)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        //请求错误
                    }

                    @Override
                    public void onSuccess(String response) {
                        ToastUtils.show("删除成功");
                        /*
                        调用setResult方法表示我将Intent对象返回给之前的那个Activity，这样就可以在onActivityResult方法中得到Intent对象，
                        */
                        //resultCode为任意值：EG:1、1000等等这里定义1346
                        Intent intent = new Intent();
//                        intent.putExtra("delete", result);
                        setResult(RESULT_CODE, intent);
                        finish();
                    }

                }) {
                });
    }


    //实现点击屏幕收起键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(ev.getAction()==MotionEvent.ACTION_DOWN){
            View v=getCurrentFocus();
            boolean  hideInputResult =isShouldHideInput(v,ev);
            Log.v("hideInputResult","zzz-->>"+hideInputResult);
            if(hideInputResult){
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) AddressActivity.this
                        .getSystemService(Activity.INPUT_METHOD_SERVICE);
                if(v != null){
                    if(imm.isActive()){
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            //之前一直不成功的原因是,getX获取的是相对父视图的坐标,getRawX获取的才是相对屏幕原点的坐标！！！
//            Log.v("leftTop[]","zz--left:"+left+"--top:"+top+"--bottom:"+bottom+"--right:"+right);
//            Log.v("event","zz--getX():"+event.getRawX()+"--getY():"+event.getRawY());
            if (event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
